<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<style>
		    *{ padding: 0; margin: 0;}
		    #box1{ width: 100px; height: 100px; background: pink; position: absolute;}
		    #box2{ width: 100px; height: 100px; background: red; position: absolute; left: 500px; top: 300px;}
		</style>
	</head>
	<body>
		<div id="box1"></div>
		<div id="box2"></div>
		<script>
    var oBox1=document.getElementById('box1');
    var oBox2=document.getElementById('box2');
    drag(oBox1)
    function drag(obj){
        obj.onmousedown=function(ev){
            var ev=ev||event;
            var dirX=ev.clientX-this.offsetLeft;
            var dirY=ev.clientY-this.offsetTop;
            
            if ( obj.setCapture ) {
            obj.setCapture();
            }
            
            document.onmousemove=function(ev){ 
              var L=ev.clientX-dirX;
              var T=ev.clientY-dirY;
              
             /* if(L<0){
                  L=0
              }else if(L>document.documentElement.clientWidth-oBox1.offsetWidth){
                  L=document.documentElement.clientWidth-oBox1.offsetWidth
              }
              if(T<0){
                  T=0
              }else if(T>document.documentElement.clientHeight-oBox1.offsetHeight){
                  T=document.documentElement.clientHeight-oBox1.offsetHeight
              }*/
             
              L=Math.min(Math.max(L,0),document.documentElement.clientWidth-obj.offsetWidth)
              T=Math.min(Math.max(T,0),document.documentElement.clientHeight-obj.offsetHeight)
             
              var L1=L;
              var R1=L+obj.offsetWidth;
              var T1=T;
              var B1=T+obj.offsetHeight;
              
              var L2 = oBox2.offsetLeft;
              var R2 = L2 + oBox2.offsetWidth;
              var T2 = oBox2.offsetTop;
              var B2 = T2 + oBox2.offsetHeight;
                  
              if(R1 < L2 || L1 > R2 || B1 < T2 || T1 > B2){
                  oBox2.style.background='red'
              }else{
                  oBox2.style.background='yellow'
              }
              
              obj.style.left=L+'px';
              obj.style.top=T+'px';
            }
            document.onmouseup=function(){
                document.onmousemove=document.onmouseup=null;
                if ( obj.releaseCapture ) {
                obj.releaseCapture();
            }
            }
            return false;
        }
    }    
</script>
	</body>
</html>
